package com.ruleengine.compiler.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruleengine.compiler.ITaskCompiler;
import com.ruleengine.compiler.exception.CompilerException;
import com.ruleengine.instruction.InstructionManager;
import com.ruleengine.instruction.InstructionSet;
import com.ruleengine.instruction.InstructionType;
import com.ruleengine.instruction.impl.GotoInstruction;
import com.ruleengine.task.ITask;
import com.ruleengine.task.config.TaskConfigManager;
import com.ruleengine.task.impl.SwitchTask;

public class SwitchTaskCompiler extends BaseCompiler<SwitchTask> {

    /*
     * (non-Javadoc)
     * 
     * @see com.wx.workflow.engine.compiler.impl.BaseCompiler#comipleSubTask(com.wx.workflow.task.ITask)
     */
    @Override
    public void comipleSubTask(SwitchTask task, InstructionSet instSet)
            throws CompilerException {
        // TODO Auto-generated method stub
        List<GotoInstruction> gotos = new ArrayList<GotoInstruction>();
        // 处理所有的when分支
        for (ITask subTask : task.getSubTasks()) {
           
            //每个子指令开始位置
            int caseSize = instSet.size();

            //编译子指令
            ITaskCompiler c = TaskConfigManager.getInstance().getTaskCompiler(
                    subTask.getTaskType());
            c.comipleTask(subTask, instSet);

            //每条子指令长度
            int subSize =  instSet.size() - caseSize;
            
            // 更新之前的goto指令的offset
            for (GotoInstruction preGoto : gotos) {
                // 先前goto指令的偏移量=原偏移量+子指令长度
                preGoto.setGotoOffset(preGoto.getGotoOffset() + subSize);
            }

            // 获取上一个when指令的附加goto指令
            GotoInstruction gotoIn = (GotoInstruction)instSet.getInstruction(instSet.size()-1);
            gotos.add(gotoIn);
        }
    }

}
